package com.example.demo.Controller;


import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.demo.common.Result;
import com.example.demo.entity.Adoption;
import com.example.demo.entity.Notification;
import com.example.demo.entity.Search;
import com.example.demo.service.IAdoptionService;
import com.example.demo.service.INotificationService;
import com.example.demo.service.ISearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author demo
 * @since 2025-03-04
 */
@RestController
@RequestMapping("/notification")
public class NotificationController {
    @Autowired
    private INotificationService notificationService;

    @Autowired
    private ISearchService searchService;

    @Autowired
    private IAdoptionService adoptionService;

    // 领养类通知接口
    @GetMapping("/listAdoption")
    public Result listAdoption(@RequestParam String userId) {
        List<Notification> list = notificationService.lambdaQuery()
                .eq(Notification::getUserId, userId)
                .eq(Notification::getType, 1) // 过滤领养类通知
                .eq(Notification::getStatus, 0)
                .orderByDesc(Notification::getCreateTime)
                .list();
        return Result.suc(list);
    }

    // 寻宠类通知接口
    @GetMapping("/listSearch")
    public Result listSearch(@RequestParam String userId) {
        List<Notification> list = notificationService.lambdaQuery()
                .eq(Notification::getUserId, userId)
                .eq(Notification::getType, 0) // 过滤寻宠类通知
                .eq(Notification::getStatus, 0)
                .orderByDesc(Notification::getCreateTime)
                .list();
        return Result.suc(list);
    }
    // 用户获取通知列表
    @GetMapping("/list")
    public Result list(@RequestParam String userId) {
        List<Notification> list = notificationService.lambdaQuery()
                .eq(Notification::getUserId, userId)
                .eq(Notification::getStatus, 0)
                .orderByDesc(Notification::getCreateTime)
                .list();
        return Result.suc(list);
    }

    @PostMapping("/process/{id}")
    public Result processNotification(@PathVariable Long id) {
        // 获取当前通知
        Notification currentNotification = notificationService.getById(id);
        if (currentNotification == null) {
            return Result.fail("通知不存在");
        }
        // 标记当前通知为已处理
        currentNotification.setStatus(1);
        notificationService.updateById(currentNotification);

        // 清除所有相同 related_id 且未处理的通知
        LambdaUpdateWrapper<Notification> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper
                .eq(Notification::getRelatedId, currentNotification.getRelatedId())
                .eq(Notification::getStatus, 0)
                .set(Notification::getStatus, 1);
        notificationService.update(updateWrapper);

        // 更新关联的 Search 记录状态为已处理
        Search search = searchService.getById(currentNotification.getRelatedId());
        if (search != null) {
            search.setStatus(2);
            searchService.updateById(search);

            // 为用户生成处理结果通知（仅在 search 非空时执行）
            Notification userNotification = new Notification();
            userNotification.setUserId(search.getOwnerNo());
            userNotification.setContent("您的宠物【" + search.getPetName() + "】已找到申请（ID: " + search.getId() + "）已被处理");
            userNotification.setStatus(1);
            userNotification.setCreateTime(LocalDateTime.now());
            userNotification.setRelatedId(search.getId());
            notificationService.save(userNotification);
        } else {
            // 可选：记录日志或返回错误信息
            System.out.println("关联的寻宠记录不存在，ID: " + currentNotification.getRelatedId());
        }

        return Result.suc("操作成功");
    }

    @PostMapping("/processAdoption/{id}")
    public Result processAdoptionNotification(
            @PathVariable Long id, // 通知ID
            @RequestBody Map<String, Object> requestBody // 拒绝理由（可选）
    ) {
        Integer applyStatus = (Integer) requestBody.get("applyStatus");
        String reason = (String) requestBody.get("reason");

        //校验：拒绝时必须提供理由
        if (applyStatus == 2 && (reason == null || reason.trim().isEmpty())) {
            return Result.fail("拒绝时必须填写理由");
        }
        //获取当前通知
        Notification notification = notificationService.getById(id);
        if (notification == null) {
            return Result.fail("通知不存在");
        }

        // 获取关联的领养申请记录
        Adoption adoption = adoptionService.getById(notification.getRelatedId());
        if (adoption == null) {
            return Result.fail("领养记录不存在");
        }

        // 如果是拒绝操作，删除领养记录
        if (applyStatus == 2) {
            adoptionService.removeById(adoption.getId());
        } else {
            // 更新领养申请状态（通过时保留记录）
            adoption.setApplyStatus(applyStatus);
            if (applyStatus == 1) {
                adoption.setStatus(200); // 假设200表示健康状态
            }
            adoptionService.updateById(adoption);
        }

        /*// 更新领养申请状态
        adoption.setApplyStatus(applyStatus);
        if (applyStatus == 1) {
            adoption.setStatus(200); // 假设200表示健康状态
        }
        adoptionService.updateById(adoption);*/

        // 清除所有关联的未处理通知
        LambdaUpdateWrapper<Notification> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper
                .eq(Notification::getRelatedId, notification.getRelatedId())
                .eq(Notification::getStatus, 0)
                .set(Notification::getStatus, 1); // 标记为已处理
        notificationService.update(updateWrapper);

        // 生成用户通知（告知处理结果）
        String userContent = applyStatus == 1 ?
                "您的领养申请【宠物" + adoption.getPetName() + "】已通过！" :
                "您的申请被拒绝，原因：" + (reason != null ? reason : "未提供理由");
        Notification userNotification = new Notification();
        userNotification.setUserId(adoption.getAdopterNo());
        userNotification.setContent(userContent);
        userNotification.setStatus(1); // 直接标记为已读
        userNotification.setCreateTime(LocalDateTime.now());
        userNotification.setRelatedId(id);
        notificationService.save(userNotification);

        return Result.suc("操作成功");
    }

    @GetMapping("/userList")
    public Result userList(@RequestParam String userId) {
        List<Notification> list = notificationService.lambdaQuery()
                .eq(Notification::getUserId, userId)
                .orderByDesc(Notification::getCreateTime)
                .list();
        return Result.suc(list);
    }

}
